// uniCloud/cloudfunctions/register/index.js
'use strict';
exports.main = async (event, context) => {
  const db = uniCloud.database()
  const { mobile, password } = event
  
  try {

    // 校验手机号格式
    const mobileReg = /^1[3-9]\d{9}$/
    if (!mobileReg.test(mobile)) {
      return { code: 4001, message: '手机号格式不正确' }
    }

    // 检查手机号是否已注册
    const { data: existUser } = await db.collection('user')
      .where({ mobile })
      .get()

    if (existUser && existUser.length > 0) {
      return { 
        code: 4002, 
        message: '该手机号已注册，请直接登录' 
      }
    }

 

    // 生成用户初始数据
    const timestamp = Date.now()
    const userData = {
      mobile,
      password,
      username: `牛友${mobile.slice(-4)}`, // 手机号后四位
      avatar: 'https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/avatar.png',
      score: 0,
      dan: 0,
      loginCount: 0,
      createTime: timestamp,
      lastLogin: timestamp,
      updateTime: new Date(timestamp).toLocaleString(),
      completedTasks: [],
      lastTaskDate: '',
      status: 1
    }

    // 写入数据库
    const res = await db.collection('user').add(userData)

    return {
      code: 0,
      message: '注册成功',
      data: {
        userId: res.id,
        mobile,
        username: userData.username
      }
    }

  } catch (error) {
    console.error('注册失败:', error)
    return {
      code: 500,
      message: '注册失败，请稍后重试',
      error: error.message
    }
  }
}